package com.haierp.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.InoutOperatorType;
import com.haierp.enums.ShippingOrderType;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.InventoryAreaMapper;
import com.haierp.mapper.InventoryMapper;
import com.haierp.mapper.InventoryRecordMapper;
import com.haierp.mapper.ItemSkuMapper;
import com.haierp.mapper.PurchaseStorageDetailMapper;
import com.haierp.model.Inventory;
import com.haierp.model.InventoryArea;
import com.haierp.model.InventoryInout;
import com.haierp.model.ItemSku;
import com.haierp.model.ShippingOrder;
import com.haierp.model.Warehouse;
import com.haierp.model.purchase.PurchaseStorage;
import com.haierp.model.purchase.PurchaseStorageDetail;
import com.haierp.service.IInventoryAreaService;
import com.haierp.service.IInventoryInoutService;
import com.haierp.service.IWarehouseService;
import com.haierp.util.JsonPageResult;
import com.haierp.util.ShiroUtil;
import com.haierp.vo.InventoryQueryVO;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.BeanUtils;

@Service("inventoryAreaService")
public class InventoryAreaServiceImpl extends SuperServiceImpl<InventoryAreaMapper, InventoryArea>
		implements IInventoryAreaService {

	@Autowired
	private InventoryAreaMapper inventoryAreaMapper;
	@Autowired
	InventoryMapper inventoryMapper;
	@Autowired
	ItemSkuMapper itemSkuMapper;
	@Autowired
	IInventoryInoutService inventoryInoutService;
	@Autowired
	IWarehouseService warehouseService;
	@Autowired
	private InventoryRecordMapper inventoryRecordMapper;
	
	@Autowired
	private PurchaseStorageDetailMapper purchaseStorageDetailMapper;
	
	@Override
	public void importPurchaseStorage(PurchaseStorage purchaseStorage) {
		List<PurchaseStorageDetail> purchaseStorageDetails = purchaseStorage.getPurchaseStorageDetailList();
		for (PurchaseStorageDetail purchaseStorageDetail : purchaseStorageDetails) {
			/*ItemSku tjItemSku = new ItemSku();
			tjItemSku.setId(purchaseStorageDetail.getSkuId());
			ItemSku selItemSku = itemSkuMapper.selectOne(tjItemSku);*/
			ItemSku selItemSku = itemSkuMapper.selectById(purchaseStorageDetail.getSkuId());

			InventoryArea inventoryArea = new InventoryArea();
			inventoryArea.setItemId(selItemSku.getItemId());
			inventoryArea.setCompanyId(selItemSku.getCompanyId());//所属公司
			inventoryArea.setSkuId(purchaseStorageDetail.getSkuId());
			inventoryArea.setItemName(selItemSku.getItemName());
			inventoryArea.setSkuCode(selItemSku.getSkuCode());
			inventoryArea.setSkuPic(selItemSku.getSkuPic());
			inventoryArea.setUpc(selItemSku.getUpc());
			inventoryArea.setColor(selItemSku.getColor());
			inventoryArea.setScale(selItemSku.getScale());
			inventoryArea.setInventory(purchaseStorageDetail.getQuantity());
			inventoryArea.setTransInv(purchaseStorageDetail.getTransQuantity());
			inventoryArea.setWarehouseId(purchaseStorageDetail.getWarehouseId());
			inventoryArea.setWarehouseName(purchaseStorageDetail.getWarehouseName());
			inventoryArea.setPositionNo(purchaseStorageDetail.getShelfNo());
			inventoryArea.setOnlineNumber(purchaseStorageDetail.getOnlineNumber());
			inventoryArea.setGmtCreate(new Date());
			inventoryArea.setGmtModify(new Date());

			this.addInventoryArea(inventoryArea,InoutOperatorType.PURCHASE_IN, "采购入库");

		}
	}

	@Override
	public void addInventoryArea(InventoryArea inventoryArea,InoutOperatorType type,String inoutReason) {
		Inventory inventory = inventoryMapper.getInventoryBySkuId(inventoryArea.getItemId(), inventoryArea.getSkuId());
		// 1、更新或插入inventoryarea
		saveInventoryArea(inventoryArea);
		// 2、记录入库日志
		String userCreate = null;
		try {
			ShiroUser su = ShiroUtil.getShiroUser();
			userCreate = su.getLoginName();
		} catch (Exception e) {
			throw new ErpCommonException("没有登入");
		}
		InventoryInout inventoryInout = BeanUtils.copy(inventoryArea, InventoryInout.class);
		inventoryInout.setInventoryAreaId(inventoryArea.getId());
		inventoryInout.setCompanyId(inventoryArea.getCompanyId());//所属公司
		inventoryInout.setQuantity(inventoryArea.getInventory());
		inventoryInout.setOperatorType(type.getCode());
		inventoryInout.setSkuCode(inventoryArea.getSkuCode());
		inventoryInout.setUserCreate(userCreate);
		inventoryInout.setInoutReason(inoutReason);//盘进盘出原因
		inventoryInout.setGmtCreate(new Date());
		inventoryInout.setGmtModify(new Date());
		if(inventoryInout.getQuantity() != 0) {
			inventoryInoutService.insert(inventoryInout);
		}
		if(inventoryArea.getTransInv() != 0) {
			inventoryInout.setQuantity(inventoryArea.getTransInv());
			inventoryInout.setOperatorType(InoutOperatorType.PURCHASE_TRANS_IN.getCode());
			inventoryInout.setOnlineNumber(inventoryArea.getOnlineNumber());
			inventoryInoutService.insert(inventoryInout);
		}

		// 3、修改Inventory库存信息
		saveInventory(inventoryArea, inventory);
	}

	@Override
	public JsonPageResult<List<InventoryArea>> queryInventoryAreas(InventoryQueryVO inventoryQueryVO) {
		JsonPageResult<List<InventoryArea>> inventoryAreaResult = new JsonPageResult<>();
		// 1、查询总的记录数量
		Integer totalCount = inventoryAreaMapper.queryInventoryAreaCount(inventoryQueryVO);
		// 2、查询分页记录
		if (totalCount != null && totalCount != 0L) {
			inventoryAreaResult.buildPage(totalCount, inventoryQueryVO);
			List<InventoryArea> inventoryAreas = inventoryAreaMapper.queryInventoryAreas(inventoryQueryVO);
			if(inventoryQueryVO.getPageIndex() == 1 && inventoryQueryVO.getSort() == null) {
				List<InventoryArea> inventoryAreasFirst = inventoryAreaMapper.queryInventoryAreasList();
				int totalAvailableInv = 0;
				int inventory = 0;
				int lockedInv = 0;
				int transInv = 0;
				int lockedTransInv = 0;
				for (InventoryArea inventoryArea : inventoryAreasFirst) {
					totalAvailableInv += inventoryArea.getTotalAvailableInv();
					inventory += inventoryArea.getInventory();
					lockedInv += inventoryArea.getLockedInv();
					transInv  += inventoryArea.getTransInv();
					lockedTransInv += inventoryArea.getLockedTransInv();
				}
				InventoryArea firstone = new InventoryArea();
				firstone.setId(0L);
				firstone.setSkuCode("明细合计");
				firstone.setInventory(inventory);
				firstone.setLockedInv(lockedInv);
				firstone.setTransInv(transInv);
				firstone.setLockedTransInv(lockedTransInv);
				firstone.setTotalAvailableInv(totalAvailableInv);
				inventoryAreas.add(firstone);
				ListSort(inventoryAreas);
			}
			for (InventoryArea inventoryArea : inventoryAreas) {
				if(inventoryArea.getTransInv() > 0) {
					EntityWrapper<PurchaseStorageDetail> entityWrapper = new EntityWrapper<PurchaseStorageDetail>();
					entityWrapper.where("sku_code={0} and shelf_no={1} and warehouse_id={2} and online_number IS NOT NULL and online_quantity > 0", inventoryArea.getSkuCode(),inventoryArea.getPositionNo(),inventoryArea.getWarehouseId());
					List<PurchaseStorageDetail> purchaseStorageList = purchaseStorageDetailMapper.selectList(entityWrapper);
					inventoryArea.setPurchaseStorageDetailList(purchaseStorageList);
					String tranDetailmark = "";
					if(purchaseStorageList.size() > 0 ) {
						for (PurchaseStorageDetail purchaseStorageDetail : purchaseStorageList) {
							  tranDetailmark  += "单号: "+purchaseStorageDetail.getOnlineNumber()+"数量: "+purchaseStorageDetail.getOnlineQuantity()+";";
						}
						inventoryArea.setTranDetailmark(tranDetailmark);
					}
				} else {
					List<PurchaseStorageDetail> purchaseStorageList = new ArrayList<PurchaseStorageDetail>();
					inventoryArea.setPurchaseStorageDetailList(purchaseStorageList);
				}
			}
			inventoryAreaResult.setData(inventoryAreas);
		} else {
			List<InventoryArea> inventoryAreas = new ArrayList<>();
			inventoryAreaResult.setData(inventoryAreas);
		}
		return inventoryAreaResult;
	}

	private void saveInventory(InventoryArea inventoryArea, Inventory inventory) {
		InventoryArea sumInventoryArea = inventoryAreaMapper.sumInventoryBySkuId(inventoryArea.getItemId(),
				inventoryArea.getSkuId());
		Date now = new Date();
		// 如果是新增，则虚拟=0，可用=实际库存， 锁定=0 ，虚拟=0 ,FIXME 新增改为商品创建初始化
		if (inventory == null) {
			insertInventory(inventoryArea, sumInventoryArea, now);
		} else {// 如果inventory存在，如 虚拟< 实际 => 虚拟设置为0 ，可用=实际-锁定 ; 虚拟 > 实际 ,最佳实际库存
			updateInventory(inventory, sumInventoryArea, now);
		}
	}

	private void updateInventory(Inventory inventory, InventoryArea sumInventoryArea, Date now) {
		int availableInv = sumInventoryArea.getTotalAvailableInv();
		inventory.setInventory(sumInventoryArea.getInventory());
		// inventory.setLockedInv(sumInventoryArea.getLockedInv());//
		// 增加库存的时候计算锁定库存是否有问题？FIXME
		inventory.setTransInv(sumInventoryArea.getTransInv());
		// 虚拟库存小于实际库存，虚拟库存清0
		if (inventory.getVirtualInv() < availableInv) {
			inventory.setVirtualInv(0);
		}
		inventory.setGmtModify(now);
		inventoryMapper.updateSelectiveById(inventory);
	}

	private void insertInventory(InventoryArea inventoryArea, InventoryArea sumInventoryArea, Date now) {
		Inventory inventory;
		inventory = new Inventory();
		inventory.setItemId(inventoryArea.getItemId());
		inventory.setCompanyId(inventoryArea.getCompanyId());
		inventory.setSkuId(inventoryArea.getSkuId());
		inventory.setItemName(inventoryArea.getItemName());
		inventory.setSkuCode(inventoryArea.getSkuCode());
		inventory.setUpc(inventoryArea.getUpc());
		inventory.setInventory(sumInventoryArea.getInventory());
		inventory.setTransInv(sumInventoryArea.getTransInv());
		// inventory.setLockedInv(0);
		// inventory.setVirtualInv(0);
		inventory.setGmtCreate(now);
		inventory.setGmtModify(now);
		inventoryMapper.insert(inventory);
	}

	private void saveInventoryArea(InventoryArea inventoryArea) {
		InventoryArea queryInventoryArea = inventoryAreaMapper.getInventoryArea(inventoryArea.getItemId(),
				inventoryArea.getSkuId(), inventoryArea.getWarehouseId(), inventoryArea.getPositionNo());
		if (queryInventoryArea == null) {
			inventoryAreaMapper.insert(inventoryArea);
		} else {
			inventoryArea.setId(queryInventoryArea.getId());
			// 在途相加
			// if(inventoryArea.getTransInv() != null){
			queryInventoryArea.setTransInv(queryInventoryArea.getTransInv() + inventoryArea.getTransInv());
			// }
			// if(inventoryArea.getInventory() != null){
			queryInventoryArea.setInventory(queryInventoryArea.getInventory() + inventoryArea.getInventory());
			// }
			queryInventoryArea.setGmtModify(new Date());
			queryInventoryArea.setColor(inventoryArea.getColor());
			queryInventoryArea.setScale(inventoryArea.getScale());
			inventoryAreaMapper.updateSelectiveById(queryInventoryArea);
		}
	}

	@Override
	public void inventoryCheckIn(Long skuId, Long warehouseId, String positionNo, Integer quantity,String inoutReason) {
		//
		ItemSku itemSku= itemSkuMapper.selectById(skuId);
		if(itemSku==null){
			throw new ErpCommonException("没有找到商品");
		}
		Warehouse warehouse=warehouseService.selectById(warehouseId);
		if(warehouse==null){
			throw new ErpCommonException("没有找到仓库");
		}
				
		if(quantity>0){
		InventoryArea inventoryArea = new InventoryArea();
		inventoryArea.setItemId(itemSku.getItemId());
		inventoryArea.setCompanyId(itemSku.getCompanyId());//库存所属公司
		inventoryArea.setSkuId(skuId);
		inventoryArea.setItemName(itemSku.getItemName());
		inventoryArea.setSkuCode(itemSku.getSkuCode());
		inventoryArea.setSkuPic(itemSku.getSkuPic());
		inventoryArea.setUpc(itemSku.getUpc());
		inventoryArea.setColor(itemSku.getColor());
		inventoryArea.setScale(itemSku.getScale());
		inventoryArea.setUpc(itemSku.getUpc());
		inventoryArea.setInventory(quantity);
		inventoryArea.setWarehouseId(warehouse.getId());
		inventoryArea.setWarehouseName(warehouse.getName());
		inventoryArea.setPositionNo(positionNo.trim());
		inventoryArea.setGmtCreate(new Date());
		inventoryArea.setGmtModify(new Date());
		
		this.addInventoryArea(inventoryArea,InoutOperatorType.CHECK_IN,inoutReason);
		}
		
	}
	
	@Override
	public List<InventoryArea> queryInventoryAreaForExcel(InventoryQueryVO inventoryQueryVO) {
		return this.baseMapper.queryInventoryAreaForExcel(inventoryQueryVO);
	}
	
	@Override
	public void changePositionNo(InventoryArea inventoryArea) {
		this.baseMapper.updateSelectiveById(inventoryArea);
		inventoryRecordMapper.changePositionNo(inventoryArea.getId(), inventoryArea.getPositionNo());
	}
	
	private static void ListSort( List<InventoryArea> list) {
		Collections.sort(list, new Comparator<InventoryArea>() {
			@Override
			public int compare(InventoryArea o1, InventoryArea o2) {
				int dt1 = o1.getTotalAvailableInv();
				int dt2 = o2.getTotalAvailableInv();
				if (dt1 > dt2) {
					return -1;
				} else if (dt1 < dt2) {
					return 1;
				} else {
					return 0;
				}
			}
		});

	}
}
